package behavioralPatterns.observer;

import java.util.ArrayList;
import java.util.List;

interface Subject {
    void register(Observer o);

    void unregister(Observer o);

    void notifyObservers();
}

interface Observer {
    void update(String msg);
}

class ConcreteSubjet implements Subject {
    private String message;
    private List<Observer> observers = new ArrayList<>();

    @Override
    public void register(Observer o) {
        observers.add(o);
    }

    @Override
    public void unregister(Observer o) {
        observers.remove(o);
    }

    @Override
    public void notifyObservers() {
        for (Observer o : observers) {
            o.update(message);
        }
    }

    public void setMessage(String message) {
        this.message = message;
        notifyObservers();
    }
}

class ConcreteObserver implements Observer {
    private String name;
    private String message;

    ConcreteObserver(String name) {
        this.name = name;
    }

    @Override
    public void update(String msg) {
        this.message = msg;
        read();
    }

    public void read() {
        System.out.println(name + " : " + message);
    }
}

public class ObserverPattern {
    public static void main(String[] args) {
        ConcreteSubjet subject = new ConcreteSubjet();
        ConcreteObserver observer1 = new ConcreteObserver("A");
        ConcreteObserver observer2 = new ConcreteObserver("B");
        ConcreteObserver observer3 = new ConcreteObserver("C");
        subject.register(observer1);
        subject.register(observer2);
        subject.register(observer3);
        subject.setMessage("Hello World!");
    }
}
